import { Service } from 'egg';
import { Teacher } from '../model/Teacher';
interface tokenType {
  username: string;
  password: string;
  type: number;
}
// 修改教师
interface updateDataType{
  id: number;
  user_id: number;
  class_id: number;
  subject: string;
}
export default class TeacherService extends Service {
  /**
   * 查询所有老师
   */
  public async queryTeacherAll(decode:tokenType, params) {
    if (decode.type !== 3) {
      return {
        code: 1,
        message: '该用户无权限操作',
        data: [],
      };
    }
    const result = await this.app.mysql.beginTransactionScope(async conn => {
      const teacherList = await conn.query(`
        SELECT teachers.id,
        teachers.user_id,
        teachers.class_id,
        users.username,
        teachers.\`subject\`,
        teachers.identity,
        teachers.type,
        classes.classname,
        teachers.created_time,
        teachers.updated_time
        FROM teachers LEFT JOIN classes ON classes.id = teachers.class_id
        LEFT JOIN users ON users.id = teachers.user_id
        WHERE users.username LIKE '%${params.username.trim()}%' 
        AND teachers.class_id LIKE '%${params.class_id}%' 
        AND teachers.type LIKE '%${params.type}%'
        AND teachers.\`subject\` LIKE '%${params.subject.trim()}%'
        LIMIT ${(params.current - 1) * params.pageSize}, ${params.pageSize}
      `);
      const pageSize = await conn.query(`
        SELECT count(*) as total
        FROM teachers LEFT JOIN classes ON classes.id = teachers.class_id
        LEFT JOIN users ON users.id = teachers.user_id
        WHERE users.username LIKE '%${params.username.trim()}%' 
        AND teachers.class_id LIKE '%${params.class_id}%' 
        AND teachers.type LIKE '%${params.type}%'
        AND teachers.\`subject\` LIKE '%${params.subject.trim()}%'
      `);
      return {
        code: 0,
        message: '操作成功',
        data: { teacherList, total: pageSize[0].total },
      };
    }, this.ctx);
    return result;
  }

  /**
   * 添加教师
   * @param teacher 教师表数据
   * @param decode token
   */
  public async addTeacher(teacher:Teacher, decode:tokenType) {
    if (decode.type !== 3) {
      return {
        code: 1,
        message: '该用户无权限操作',
        data: [],
      };
    }
    const result = await this.app.mysql.beginTransactionScope(async conn => {
      const teacherArr:Teacher[] = await conn.select('teachers', { where: { user_id: teacher.user_id, subject: teacher.subject.trim() } }) as Teacher[];
      if (teacherArr.length !== 0) {
        return {
          code: 1,
          message: '该教师已存在',
          data: [],
        };
      }
      await conn.insert('teachers', {
        user_id: teacher.user_id,
        class_id: teacher.class_id,
        subject: teacher.subject.trim(),
        type: 0,
        created_time: new Date(),
        updated_time: new Date(),
      });
      return {
        code: 0,
        message: '添加成功',
        data: [],
      };
    }, this.ctx);
    return result;
  }


  /**
   * 删除教师
   * @param id 教师id
   */
  public async delTeacher(id:number, decode:tokenType) {
    if (decode.type !== 3) {
      return {
        code: 1,
        message: '该用户无权限操作',
        data: [],
      };
    }
    const result = await this.app.mysql.beginTransactionScope(async conn => {
      const teachers:Teacher[] = await conn.select('teachers', { where: { id } }) as Teacher[];
      if (teachers.length === 0) {
        return {
          code: 1,
          message: '该教师不存在',
          data: [],
        };
      }
      const hasTeacher = await conn.select('teachers', { where: { user_id: teachers[0].user_id } }) as Teacher[];
      if (hasTeacher.length === 1) {
        return {
          code: 1,
          message: '该用户至少执教一个班级',
          data: [],
        };
      }
      await conn.delete('teachers', { id });
      return {
        code: 0,
        message: '删除成功',
        data: [],
      };
    }, this.ctx);
    return result;
  }

  /**
   * 修改教师
   * @param data 教师表单
   * @param decode 用户信息
   */
  public async updateTeacher(data:updateDataType, decode:tokenType) {
    if (decode.type !== 3) {
      return {
        code: 1,
        message: '该用户无权限操作',
        data: [],
      };
    }
    const result = await this.app.mysql.beginTransactionScope(async conn => {
      const teacher = await conn.select('teachers', { id: data.id });
      if (teacher.length === 0) {
        return {
          code: 1,
          message: '该教师不存在',
          data: [],
        };
      }
      const isChanges = await conn.select('teachers', { where: { id: data.id, subject: data.subject, user_id: data.user_id, class_id: data.class_id } });
      if (isChanges.length !== 0) {
        return {
          code: 1,
          message: '修改的内容已存在',
          data: [],
        };
      }
      await conn.update('teachers', data, { id: data.id });
      return {
        code: 0,
        message: '修改成功',
        data: [],
      };
    }, this.ctx);
    return result;
  }

}

